﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMN.Common;
using System.Web.Security;
using CMN.Framework;
using CMN.Entity;

using System.Configuration;
using System.Diagnostics;
using System.Globalization;
namespace CMN.Controllers.Filters
{
    public class ExecutionTimingAttribute : ActionFilterAttribute
    {
        private bool timingEnabled 
        {
            get
            {
                bool rbool = false;
                if (ConfigurationManager.AppSettings["TimingEnabled"] != null)
                {
                    bool.TryParse(ConfigurationManager.AppSettings["TimingEnabled"].ToString(), out rbool);
                }
                return rbool;
            }
         }
        private Stopwatch timer;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (this.timingEnabled)
            {
                this.timer = new Stopwatch();
                this.timer.Start();
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            if (this.timingEnabled)
            {
                this.timer.Stop();
                if (timer.ElapsedMilliseconds > 2000)
                {
                    Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Action execution time: {0}ms", this.timer.ElapsedMilliseconds));
                    if (filterContext.Result is ViewResult)
                    {
                        ((ViewResult)filterContext.Result).ViewData["ExecutionTime"] = this.timer.ElapsedMilliseconds;
                    }
                    string controller = filterContext.RequestContext.RouteData.Values["controller"].ToString();
                    string action = filterContext.RequestContext.RouteData.Values["action"].ToString();
                    AppLog.Write(string.Concat(controller, ":", action, Utils.GetIP(), "用时", this.timer.ElapsedMilliseconds.ToString()), AppLog.LogMessageType.Debug);
                }
            }
        }
    } 
}